const Router = require('koa-router')
const {
    success,
    notFound
} = require('../../../core/http-exception')
const {
    tokenFn
} = require('../../../core/util')
const Auth = require('../../../middlewares/auth')
const {
    loginType
} = require('../../lib/enum')
const {
    User
} = require('../../models/user')
const {
    isToken, isAccessToken
} = require('../../validators')
const router = new Router({
    prefix: '/api/token'
})
const jwt = require('jsonwebtoken')
const config = require('../../../config')
/**
 * @swagger
 * /api/token: # 接口地址
 *   post: # 请求体
 *     description: 获取refreshToken # 接口信息
 *     tags: [用户鉴权模块] # 模块名称
 *     parameters: # 请求参数
 *       - name: body
 *         description: 账号密码
 *         in: body # 参数的位置，可能的值有 "query", "header", "path" "cookie" "body" "formData"
 *         schema:
 *           type: "object"
 *           properties:
 *              account:
 *                type: string
 *                description: "账号"
 *                enum: 
 *                  - 1393248850@qq.com
 *              type:
 *                type: number
 *                description: "类型"
 *                enum: 
 *                  - 103
 *                  - 101
 *                  - 102
 *                  - 100
 *              secret:
 *                type: string
 *                description: "密码"
 *                enum: 
 *                  - 314159Ax
 *         required: true
 *     responses:
 *       '200':
 *         description: token信息
 */
 router.post('/', async ctx => {
    const v = await new isToken().validate(ctx)
    let response;
    switch (v.get('body.type')) {
        case loginType.thirdParty:
            break
        case loginType.email:
            break
        case loginType.account:
            console.log(Auth.user)
            response = await accountLogin(v.get('body.account'), v.get('body.secret'), Auth.user)
            break
        case loginType.mobile:
            break
        default:
            throw new notFound('该登录方式暂未开发！')
    }
    throw new success({
        response
    })
})


router.post('/accessToken', async ctx => {
    const v = await new isAccessToken().validate(ctx)
   let token = v.get('body.refreshToken')
    var decode = await jwt.verify(token, config.refreshToken.secretKey)
    throw new success({
        response:tokenFn(decode.uid,decode.scope,'accessToken')
    })
})

async function accountLogin(account, secret, auth) {
    const user = await User.verifyAccount(account, secret)
    return tokenFn(user.dataValues.id, auth,'refreshToken')
}



module.exports = router